package zhaolu.com.example.Delicacy.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import zhaolu.com.example.Delicacy.Entity.Customer;
import zhaolu.com.example.Delicacy.MySQL.CustomerDAO;
import zhaolu.com.example.Delicacy.R;
import zhaolu.com.example.Delicacy.Utils.CommonUtils;

public class MainActivity extends AppCompatActivity {
    private long exitTime;
    private Button bt_login;
    private Button bt_register;
    private EditText et_phone;
    private EditText et_password;
    private TextView tv_manager;
    private Handler mainHandler;
    private CustomerDAO customerDAO;
    private BottomNavigationView bottomNavigationView;

    private void initView() {
        bt_login = findViewById(R.id.login_button);
        bt_register = findViewById(R.id.register_button);
        et_phone = findViewById(R.id.et_phone);
        et_password = findViewById(R.id.et_password);
        tv_manager = findViewById(R.id.manager_login);
        customerDAO = new CustomerDAO();
        mainHandler = new Handler(getMainLooper());

        bt_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getId() == R.id.register_button) {
                    try {
                        doRegister();
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getId() == R.id.login_button) {
                    try {
                        doLogin();
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        tv_manager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ComponentName componentname = new ComponentName(MainActivity.this, ManagerLoginActivity.class);
                Intent intent = new Intent();
                intent.setComponent(componentname);
                startActivity(intent);
            }
        });
    }

    private void doLogin() throws NoSuchAlgorithmException {
        final String phone = et_phone.getText().toString().trim();
        final String password = et_password.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            CommonUtils.showShortMsg(this, "请输入用户名！");
            et_phone.requestFocus();
        } else if (TextUtils.isEmpty(password)) {
            CommonUtils.showShortMsg(this, "请输入密码！");
            et_password.requestFocus();
        } else {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(password.getBytes(StandardCharsets.UTF_8));
            String cipher_password = new BigInteger(messageDigest.digest()).toString(16);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final Customer item = customerDAO.getCustomerByUserAndPassword(phone, cipher_password);
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (item == null) {
                                CommonUtils.showDlgMsg(MainActivity.this, "用户名或密码错误！");
                            } else {
                                // 传递登录信息
                                SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
                                sp.edit()
                                        .putString("username", phone)
                                        .putString("password", password)
                                        .apply();
                                CommonUtils.showShortMsg(MainActivity.this, "登陆成功！");
                                // 跳转页面
                                Intent intent = new Intent(MainActivity.this, FragmentActivity.class);
                                startActivity(intent);
                            }
                        }
                    });
                }
            }).start();
        }
    }

    private void doRegister() throws NoSuchAlgorithmException {
        final String phone = et_phone.getText().toString().trim();
        final String password = et_password.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            CommonUtils.showShortMsg(this, "请输入用户名！");
            et_phone.requestFocus();
        } else if (TextUtils.isEmpty(password)) {
            CommonUtils.showShortMsg(this, "请输入密码！");
            et_password.requestFocus();
        } else {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(password.getBytes(StandardCharsets.UTF_8));
            String cipher_password = new BigInteger(messageDigest.digest()).toString(16);
            Customer item = new Customer();
            item.setId(phone);
            item.setPassword(cipher_password);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final int iRow = customerDAO.addCustomer(item);
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            CommonUtils.showShortMsg(MainActivity.this, "注册成功！");
                        }
                    });
                }
            }).start();
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(MainActivity.this, "再次返回程序退出！", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        initView();
    }
}